package com.sl.au.service.impl;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.sl.au.entity.Option;
import com.sl.au.entity.ReceivedPaymentTotalInfo;
import com.sl.au.entity.ReceivedPaymentTotalInfoFictitious;
import com.sl.au.entity.User;
import com.sl.au.repository.OptionRepository;
import com.sl.au.repository.ReceivedPaymentTotalInfoRepository;
import com.sl.au.repository.UserRepository;
import com.sl.au.service.ReceivedPaymentTotalInfoService;
import com.sl.au.service.ExcelService;
import com.sl.au.service.OperateLogService;

@Service("ReceivedPaymentTotalInfoService")
@Transactional
public class ReceivedPaymentTotalInfoServiceImpl extends BaseServiceImpl implements ReceivedPaymentTotalInfoService {
	@Autowired
	private ReceivedPaymentTotalInfoRepository receivedPaymentTotalInfoRepository;
	@Autowired
	private OperateLogService operateLogService;
	@Autowired
	UserRepository userRepository;
	@Autowired
	OptionRepository optionRepository;
	@Autowired
	ExcelService excelService;
	@Override
	public ReceivedPaymentTotalInfoRepository getRepository()
	{
	   return	this.receivedPaymentTotalInfoRepository;
	}
	
	@Override
	public List<ReceivedPaymentTotalInfo> getPage(int start, int length, String key)
	{
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.ASC, "dReceivedPaymentsDate");
		Page<ReceivedPaymentTotalInfo> pages = receivedPaymentTotalInfoRepository.getPage(key, pageable);
		return pages.getContent();		
	}
	
	@Override
	public long getCount(String key)
	{
		long count =receivedPaymentTotalInfoRepository.getCount(key);
		return count;
	}
    
	// 验证组名唯一性
	private int validatesReceivedPaymentsIdentifyNumber(ReceivedPaymentTotalInfo receivedPaymentTotalInfo) {
		
		int code = 0;
		ReceivedPaymentTotalInfo old = this.receivedPaymentTotalInfoRepository.findBySReceivedPaymentsIdentifyNumber(receivedPaymentTotalInfo.getsReceivedPaymentsIdentifyNumber());
		
		if (null != old) {
			if (!receivedPaymentTotalInfo.getId().equals(old.getId()))
				code = 1;
		}
		
		return code;
	}
			
	@Override
	public int save(ReceivedPaymentTotalInfo receivedPaymentTotalInfo, User user) {
		int code=validatesReceivedPaymentsIdentifyNumber(receivedPaymentTotalInfo);
		if(code==0){
			this.receivedPaymentTotalInfoRepository.save(receivedPaymentTotalInfo);
			operateLogService.log(user, "新增回款", "新增回款"+receivedPaymentTotalInfo.getsReceivedPaymentsIdentifyNumber());
		}
		return code;
	}
	
	@Override
	public int delete(String id, User user) throws Exception {
		int code=1;
		ReceivedPaymentTotalInfo old = receivedPaymentTotalInfoRepository.findOne(id);
		
		if(null!=old){
			receivedPaymentTotalInfoRepository.delete(old);
			code=0;
			operateLogService.log(user, "删除回款", "删除了回款"+old.getsReceivedPaymentsIdentifyNumber());
		}
		
		return code;
	}
	@Override
	public int patch(ReceivedPaymentTotalInfo receivedPaymentTotalInfo, User user) {
		int code=validatesReceivedPaymentsIdentifyNumber(receivedPaymentTotalInfo);
		if(code==0){
			ReceivedPaymentTotalInfo old = this.receivedPaymentTotalInfoRepository.findOne(receivedPaymentTotalInfo.getId());
			
			if(null!=old){
				BeanUtils.copyProperties(receivedPaymentTotalInfo, old, "createTime");
				this.receivedPaymentTotalInfoRepository.save(old);
				operateLogService.log(user, "修改回款", "修改了回款"+old.getsReceivedPaymentsIdentifyNumber());
			}			
		}
		
		
		
		return code;
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public String importExcel(String fileName,User user) {
		String count = "";
		if (!StringUtils.hasText(fileName))
			return count;
		Map<String, Object> collections = new HashMap<>();
		// excelService.setStorageLocation(CRM.getStorageLocation());
		
		excelService.importExcel("receivedPaymentTotalInfo", collections, fileName);
		if (collections.size() < 1 || collections.get("items") == null)
			return count;
		List<ReceivedPaymentTotalInfoFictitious> rows = (List<ReceivedPaymentTotalInfoFictitious>) collections.get("items");
		List<ReceivedPaymentTotalInfo> ReceivedPaymentTotalInfos = new ArrayList<ReceivedPaymentTotalInfo>();
		if (null != rows && rows.size() > 0) {
			for (int i = 0;i < rows.size(); i++) {
				ReceivedPaymentTotalInfoFictitious received = rows.get(i);
				ReceivedPaymentTotalInfo newReceived = new ReceivedPaymentTotalInfo();
				newReceived.setsReceivedPaymentsNetworkNumer(received.getsReceivedPaymentsIdentifyNumber());
				if(!received.getsReceivedPaymentsIdentifyType().equals("") && received.getsReceivedPaymentsIdentifyType() != null){
					String title = received.getsReceivedPaymentsIdentifyType();
					List<Option> options = optionRepository.findByGroupAndTitle("凭证种类", title);
					if(options == null || options.size() < 1){
						count = "第" + (i+2) + "行的凭证种类不存在，请核实后导入。";
						return count;
					}else if(options.size() == 1){
						newReceived.setsReceivedPaymentsIdentifyType(options.get(0));
					}else if(options.size() > 1){
						newReceived.setsReceivedPaymentsIdentifyType(options.get(options.size() - 1));
					}else{
						count = "第" + (i+2) + "行的凭证种类不存在，请核实后导入。";
						return count;
					}
				}
				if(!received.getdReceivedPaymentsDate().equals("") && received.getdReceivedPaymentsDate() != null){
					Pattern pattern = Pattern.compile("^[0-9]*$"); 
					Calendar c = new GregorianCalendar(1900,0,-1);  
					Date d = c.getTime();  
					if (pattern.matcher(received.getdReceivedPaymentsDate()).matches() == true && Integer.parseInt(received.getdReceivedPaymentsDate()) > 36524){
						int z = Integer.parseInt(received.getdReceivedPaymentsDate());
						Date _d = DateUtils.addDays(d, z);  //42605是距离1900年1月1日的天数
						newReceived.setdReceivedPaymentsDate(_d);
					}else{
						count = "第" + (i+2) + "行的时间格式不正确，请修改后导入。";
						return count;
					}
					//Date d = new Date(Integer.parseInt(received.getdReceivedPaymentsDate()));
				}
				if(!received.getnReceivedPaymentActualPrice().equals("") && received.getnReceivedPaymentActualPrice() != null){
					String s = received.getnReceivedPaymentActualPrice();
					Pattern pattern = Pattern.compile("^[0-9]*$"); 
					if (pattern.matcher(s).matches() == true)
					{
						newReceived.setnReceivedPaymentActualPrice(Double.valueOf(received.getnReceivedPaymentActualPrice()));
					}
					else
					{
						count = "第" + (i+2) + "行的回款金额不是小数，请修改后导入。";
						return count;
					}
				}
				newReceived.setsReceivedPaymentsIdentifyNumber(received.getsReceivedPaymentsIdentifyNumber());
				newReceived.setsReceivedPaymentsName(received.getsReceivedPaymentsName());
				newReceived.setsReceivedPaymentsAccount(received.getsReceivedPaymentsAccount());
				newReceived.setsReceivedPaymentsCustomerName(received.getsReceivedPaymentsCustomerName());
				newReceived.setsReceivedPaymentsCustomerAccount(received.getsReceivedPaymentsCustomerAccount());
				newReceived.setsReceivedPaymentTradeType(received.getsReceivedPaymentTradeType());
				newReceived.setsReceivedPaymentMemo(received.getsReceivedPaymentMemo());
				newReceived.setsReceivedPaymentTradeWay(received.getsReceivedPaymentTradeWay());
				newReceived.setsReceivedPaymentPersonId(user.getEmpLogin().getEmpId());
				newReceived.setsCreateUserId(user.getId());
				ReceivedPaymentTotalInfos.add(newReceived);
			}
			this.receivedPaymentTotalInfoRepository.save(ReceivedPaymentTotalInfos);
			count = "成功导入" + rows.size() + "条数据。";
		}
		return count;
	}
}
